import { useRef, useEffect, DependencyList } from "react";
import isEqual from "lodash/fp/isEqual";

type EffectHookType = typeof useEffect;
type CreateUpdateEffect = (hook: EffectHookType) => EffectHookType;

export const createDeepCompareEffect: CreateUpdateEffect =
  (effect) => (callback, deps) => {
    const ref = useRef<DependencyList>();
    const signalRef = useRef<number>(0);

    if (deps === undefined || !isEqual(deps, ref.current)) {
      ref.current = deps;
      signalRef.current += 1;
    }

    effect(callback, [signalRef.current]);
  };

export default createDeepCompareEffect(useEffect);
